package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private INoticeService noticeService;

    @Override
    public void save(Notice notice) {
        notice.setCreateMen(UserContext.getCurrentUser().getUsername());
        notice.setCreateTime(new Date());
        notice.setStatus(false);
        noticeMapper.insert(notice);

//        插入中间表
        noticeMapper.insertRelation(notice.getId(),UserContext.getCurrentUser().getId());
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteRelation(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void updateRead(Long id,Long uId) {
        noticeMapper.updateRead(id,uId);
    }

    @Override
    public void deliver(Long id) {
        List<Employee> employees = employeeMapper.selectAll();
//        往中间表插入数据
        for (Employee e:employees){
             List<Long> uIds = noticeMapper.selectRelation(id);
            if(!uIds.contains(e.getId())){
                noticeMapper.insertRelation(id,e.getId());
            }
        }
//        将该公告状态改成发布 和 设置发布时间
        noticeMapper.updateStatus(id,new Date());

    }


}
